// AppFragment.kt
package com.ityun.ogapp.fragment

import android.os.Handler
import android.os.Looper
import android.util.Log
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.lifecycle.lifecycleScope
import com.ityun.ogapp.R
import com.ityun.ogapp.base.BaseFragment
import com.ityun.ogapp.databinding.FragmentAppBinding
import com.ityun.ogapp.utils.NetworkUtils
import com.ven.assists.stepperx.Step.Companion.launch
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

class AppFragment : BaseFragment<FragmentAppBinding>() {
    private var networkCheckJob: Job? = null
    private val handler = Handler(Looper.getMainLooper())
    private val checkInterval = 10000L // 10秒
    override fun createViewBinding(
        inflater: LayoutInflater,
        container: ViewGroup?
    ): FragmentAppBinding {
        return FragmentAppBinding.inflate(inflater, container, false)
    }

    override fun initViews() {
        super.initViews()
        searchNetWork()
        startNetworkStatusTimer()
        Log.d("AppFragment", NetworkUtils.isWifiEnabled(requireContext()).toString())
        Log.d("AppFragment", NetworkUtils.isMobileDataEnabled(requireContext()).toString())
        Log.d("AppFragment", NetworkUtils.isAirplaneModeOn(requireContext()).toString())
    }


    private fun searchNetWork() {
        // 启动网络状态监控
        launch {
            NetworkUtils.monitorNetworkAvailability(requireContext())
                .collect { isAvailable ->
                    // 在主线程中处理网络状态变化
                    requireActivity().runOnUiThread {
                        if (isAvailable) {
                            // 网络可用时的处理
                            mBinding.tvNetStatus.text = getString(R.string.network_can_use)
                        } else {
                            // 网络不可用时的处理
                            mBinding.tvNetStatus.text =
                                getString(R.string.network_no_use)
                        }
                    }
                }
        }
    }

    private fun startNetworkStatusTimer() {
        networkCheckJob = lifecycleScope.launch {
            while (true) {
                delay(checkInterval)
                checkNetworkStatus()
            }
        }
    }

    private fun checkNetworkStatus() {
        val isWifiEnabled = NetworkUtils.isWifiEnabled(requireContext())
        val isMobileDataEnabled = NetworkUtils.isMobileDataEnabled(requireContext())
        requireActivity().runOnUiThread {

            Log.d("AppFragment", "WiFi Enabled: $isWifiEnabled")
            Log.d("AppFragment", "Mobile Data Enabled: $isMobileDataEnabled")
        }
    }
}
